package com.heima.schedule.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.google.gson.JsonObject;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import com.mysql.jdbc.log.Log;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author ZQH
 * @version 1.0
 * @date 2023/8/20 17:21
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TaskServiceImpl implements TaskService {


    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加延时任务
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {
        //添加任务到数据库中
        boolean addTaskToDb = addTaskToDb(task);
        if (addTaskToDb){
            //添加任务到redis
            addTaskToCache(task);
        }


        return task.getTaskId();
    }


    /**
     * 拉取任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type+"-"+priority;
        Task task = null;
        try {
            //从redis中拉取任务数据
            String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (!StringUtils.isEmpty(taskJson)){
                task = JSONObject.parseObject(taskJson, Task.class);
                //修改数据库内容
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception exception) {
            log.error("poll拉取任务异常：{}",exception);
        }
        return task;
    }

    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);

        //删除 redis 数据
        if (task != null){
            removeTaskFrokCache(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 删除redis 中的数据
     * @param task
     */
    private void removeTaskFrokCache(Task task) {
        String key = task.getTaskType()+"-"+task.getPriority();
        if (task.getExecuteTime()<= System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key, 0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());

        }
    }

    /**
     * 删除任务、更新任务日志
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);
            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            task = new Task();
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception exception) {
            log.info("updateDb异常信息：{}",exception);
        }
        return task;
    }


    @Autowired
    private CacheService cacheService;
    /**
     * 添加任务到redis
     *如果当前任务的执行时间小于等于当前时间存入list
     * 如果任务的执行时间大于当前时间存入set
     * @param task
     */
    private void addTaskToCache(Task task) {
        String key = task.getTaskType()+"-"+task.getPriority();

        //获取五分钟之后的时间（毫秒值）
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextScheduleTime = calendar.getTimeInMillis();

        if (task.getExecuteTime()<= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if (task.getExecuteTime() <= nextScheduleTime){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());

        }

    }


    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task){
        boolean flag = false;
        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskId
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            log.error("addTaskToDb异常:{}",e);
        }
        return flag;
    }


    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){

        String token = cacheService.tryLock(ScheduleConstants.FUTURE + "TASK_SYNC", 30 * 1000);
        if (!StringUtils.isEmpty(token)){
            log.info("未来数据定时刷新----------定时任务");
            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {

                //获取当前数据的key topic
                String topicKey = ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];
                //按照key和分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                //同步数据
                if (!StringUtils.isEmpty(tasks)){
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                    log.info("成功的将：{},{}",futureKey,"刷新到了"+topicKey);
                }
            }
        }

    }

    /**
     * 数据库任务定时同步到redis
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadDate(){
        //清理缓存中的数据
        clearCache();
        //查询符合条件的任务 小于未来五分钟的任务
        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime, calendar.getTime()));
        //把任务添加到redis中
        if (taskinfos != null && taskinfos.size() >0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
        log.info("数据库中的任务同步到redis");

    }

    /**
     * 清理缓存中的数据
     */
    public void clearCache(){
        Set<String> topicKey = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKey = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKey);
        cacheService.delete(futureKey);
    }

}
